// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/testing/functions/prestosql/function_base_test.h>

using namespace kumo::pollux;
using namespace kumo::pollux::test;

class TransformTest : public functions::test::FunctionBaseTest {};

TEST_F(TransformTest, basic) {
  vector_size_t size = 1'000;
  auto input = make_row_vector(
      {make_array_vector<int64_t>(size, modN(5), modN(7), null_every(11))});

  auto result = evaluate<ArrayVector>("transform(c0, x -> x + 5)", input);

  auto expectedResult = make_array_vector<int64_t>(
      size,
      modN(5),
      [](vector_size_t row) { return row % 7 + 5; },
      null_every(11));
  assertEqualVectors(expectedResult, result);
}

TEST_F(TransformTest, evaluateSubsetOfRows) {
  // Test to verify that output complex vector of valid internal state is
  // generated when only a subset of the rows are evaluated. To simulate this,
  // the trailing rows are unselected to generate an elements vector of smaller
  // size so that indices for those rows would point to out of bounds location
  // in elements vector.
  vector_size_t size = 100;
  auto input = make_row_vector(
      {make_array_vector<int64_t>(size, modN(5), modN(7), null_every(11))});

  // Test using 2 selectivity vectors. One of size 100 with 33 first rows
  // selected. Another of size 33 with all rows selected. Both should produce
  // the same result.

  auto expectedResult = make_array_vector<int64_t>(
      size / 3,
      modN(5),
      [](vector_size_t row) { return row % 7 + 5; },
      null_every(11));
  {
    SelectivityVector inputRows(size, false);
    inputRows.setValidRange(0, size / 3, true);
    inputRows.updateBounds();

    auto result =
        evaluate<ArrayVector>("transform(c0, x -> x + 5)", input, inputRows);
    assertEqualVectors(expectedResult, result, inputRows);
  }

  {
    SelectivityVector inputRows(size / 3);

    auto result =
        evaluate<ArrayVector>("transform(c0, x -> x + 5)", input, inputRows);
    assertEqualVectors(expectedResult, result, inputRows);
  }
}

TEST_F(TransformTest, differentResultType) {
  vector_size_t size = 1'000;
  auto input = make_row_vector(
      {make_array_vector<int64_t>(size, modN(5), modN(7), null_every(11))});

  auto result = evaluate<ArrayVector>("transform(c0, x -> (x % 2 = 0))", input);

  auto expectedResult = make_array_vector<bool>(
      size,
      modN(5),
      [](auto row) { return (row % 7) % 2 == 0; },
      null_every(11));
  assertEqualVectors(expectedResult, result);
}

// Test different lambdas applied to different rows
TEST_F(TransformTest, conditional) {
  vector_size_t size = 1'000;

  // make 2 columns: the array to transform and a boolean that decided which
  // lambda to use
  auto is_null_at = null_every(11);
  auto inputArray = make_array_vector<int64_t>(size, modN(5), modN(7), is_null_at);
  auto condition =
      make_flat_vector<bool>(size, [](auto row) { return row % 3 == 1; });
  auto input = make_row_vector({condition, inputArray});

  auto result = evaluate<ArrayVector>(
      "transform(c1, if (c0, x -> x + 5, x -> x - 3))", input);

  // make 2 expected vectors: one for rows where condition is true and another
  // for rows where condition is false
  auto expectedPlus5 = make_array_vector<int64_t>(
      size, modN(5), [](auto row) { return row % 7 + 5; }, is_null_at);
  auto expectedMinus3 = make_array_vector<int64_t>(
      size, modN(5), [](auto row) { return row % 7 - 3; }, is_null_at);
  ASSERT_EQ(size, result->size());
  for (auto i = 0; i < size; i++) {
    if (i % 3 == 1) {
      ASSERT_TRUE(expectedPlus5->equal_value_at(result.get(), i, i))
          << "at " << i << ": " << expectedPlus5->toString(i) << " vs. "
          << result->toString(i);

    } else {
      ASSERT_TRUE(expectedMinus3->equal_value_at(result.get(), i, i))
          << "at " << i << ": " << expectedMinus3->toString(i) << " vs. "
          << result->toString(i);
    }
  }
}

TEST_F(TransformTest, dictionaryWithUniqueValues) {
  vector_size_t size = 1'000;
  auto inputArray =
      make_array_vector<int32_t>(size, modN(5), modN(7), null_every(11));

  auto indices = make_indices_in_reverse(size);
  auto input = make_row_vector(
      {make_flat_vector<int16_t>(size, [](auto /* row */) { return 5; }),
       wrap_in_dictionary(indices, size, inputArray)});

  auto result = evaluate<BaseVector>("transform(c1, x -> x + c0)", input);

  auto expectedResult = wrap_in_dictionary(
      indices,
      size,
      make_array_vector<int32_t>(
          size, modN(5), [](auto row) { return row % 7 + 5; }, null_every(11)));
  assertEqualVectors(expectedResult, result);
}

TEST_F(TransformTest, dictionaryWithDuplicates) {
  vector_size_t size = 1'000;

  // make an array vector where each row repeats a few times
  auto baseArray =
      make_array_vector<int32_t>(size / 2, modN(5), modN(7), null_every(11));

  BufferPtr indices = allocate_indices(size, execCtx_.pool());
  auto rawIndices = indices->asMutable<vector_size_t>();
  for (auto i = 0; i < size; ++i) {
    rawIndices[i] = i / 2;
  }

  auto array = wrap_in_dictionary(indices, size, baseArray);

  // make a capture with unique values
  auto capture = make_flat_vector<int32_t>(size, [](auto row) { return row; });

  auto input = make_row_vector({capture, array});

  auto result = evaluate<BaseVector>("transform(c1, x -> x + c0)", input);

  auto flatArray = flatten(array);
  input = make_row_vector({capture, flatArray});
  auto expectedResult =
      evaluate<BaseVector>("transform(c1, x -> x + c0)", input);

  assertEqualVectors(expectedResult, result);
}

TEST_F(TransformTest, try) {
  auto input = make_row_vector({
      make_array_vector<int64_t>({
          {6, 4},
          {2, 0},
          {-2, -4},
      }),
  });

  ASSERT_THROW(
      evaluate<ArrayVector>("transform(c0, x -> x / (x - 2))", input),
      std::exception);

  auto result =
      evaluate<ArrayVector>("try(transform(c0, x -> x / (x - 2)))", input);

  auto expectedResult = vectorMaker_.array_vector_nullable<int64_t>({
      {{1, 2}},
      std::nullopt,
      {{0, 0}},
  });
  assertEqualVectors(expectedResult, result);
}
